/**
 * Copyright (c) 2020 kedacom
 * OpenATC is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 * http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 **/
/**
 * Created by jiachenpan on 16/11/18.
 */

export function parseTime (time, cFormat) {
  if (arguments.length === 0) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if (('' + time).length === 10) time = parseInt(time) * 1000
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const timeStr = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key]
    if (key === 'a') return ['一', '二', '三', '四', '五', '六', '日'][value - 1]
    if (result.length > 0 && value < 10) {
      value = '0' + value
    }
    return value || 0
  })
  return timeStr
}

export function formatTime (time, option) {
  time = +time * 1000
  const d = new Date(time)
  const now = Date.now()

  const diff = (now - d) / 1000

  if (diff < 30) {
    return '刚刚'
  } else if (diff < 3600) { // less 1 hour
    return Math.ceil(diff / 60) + '分钟前'
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + '小时前'
  } else if (diff < 3600 * 24 * 2) {
    return '1天前'
  }
  if (option) {
    return parseTime(time, option)
  } else {
    return d.getMonth() + 1 + '月' + d.getDate() + '日' + d.getHours() + '时' + d.getMinutes() + '分'
  }
}

// 数字0~9对应的ASCII码值是 48-57
// 大写字母A-Z对应的ASCII码值是 65-90
// 小写字母a-z对应的ASCII码值是 97-122
export function createRandomKey (legnth) {
  // 定义一个空数组保存我们的密码
  let passArrItem = []

  // 定义获取密码成员的方法
  const getNumber = () => Math.floor(Math.random() * 10) // 0~9的数字
  const getUpLetter = () => String.fromCharCode(Math.floor(Math.random() * 26) + 65) // A-Z
  const getLowLetter = () => String.fromCharCode(Math.floor(Math.random() * 26) + 97) // a-z

  // 将获取成员的方法保存在一个数组中方便用后面生成的随机index取用
  const passMethodArr = [getNumber, getUpLetter, getLowLetter]

  // 随机index
  const getIndex = () => Math.floor(Math.random() * 3)

  // 从0-9，a-z，A-Z中随机获取一项
  const getPassItem = () => passMethodArr[getIndex()]()

  Array(legnth - 3).fill('').forEach(() => {
    passArrItem.push(getPassItem())
  })

  const confirmItem = [getNumber(), getUpLetter(), getLowLetter()]

  // 加上我们确认的三项，从而使生成的密码，大写字母、小写字母和数字至少各包含一个
  passArrItem.push(...confirmItem)

  // 转为字符串返回
  return passArrItem.join('')
}
